/**
 * 健康数据API模块
 * 处理血糖、血压、体重等健康数据的CRUD操作
 */

const request = require('./request');

// API访问存储库
const storage = {
  glucose: [],
  bloodPressure: [],
  weight: []
};

// 是否已经初始化数据的标志
let dataInitialized = false;

// 风险评估记录存储
const riskAssessmentStorage = [];

// 初始化数据函数
function initializeData(forceReset = false) {
  // 如果已经初始化过且不是强制重置，则直接返回
  if (dataInitialized && !forceReset) {
    console.log('[健康API] 数据已经初始化过，跳过初始化过程');
    return;
  }
  
  console.log('[健康API] 开始初始化测试数据，forceReset =', forceReset);
  const now = new Date();
  now.setHours(23, 59, 59, 999);  // 设置为今天结束
  const day = 24 * 60 * 60 * 1000;
  
  // 清空现有数据
  storage.glucose = [];
  storage.bloodPressure = [];
  storage.weight = [];
  console.log('[健康API] 已清空现有数据，开始生成新数据');
  
  // 生成最近30天的数据
  for (let i = 0; i < 30; i++) {
    const date = new Date(now - i * day);
    
    // 早上数据 (8:00)
    date.setHours(8, 0, 0, 0);
    
    // 血糖数据
    storage.glucose.push({
      timestamp: date.getTime(),
      value: parseFloat((Math.random() * 3 + 5).toFixed(1)),
      period: 'morning'
    });
    
    // 添加血压数据 (8:00)
    storage.bloodPressure.push({
      timestamp: date.getTime(),
      systolic: Math.floor(Math.random() * 30 + 110),  // 收缩压范围110-140
      diastolic: Math.floor(Math.random() * 20 + 70),  // 舒张压范围70-90
      period: 'morning'
    });
    
    // 添加体重数据 (8:00) - 每天早上测量一次
    storage.weight.push({
      timestamp: date.getTime(),
      value: parseFloat((Math.random() * 10 + 60).toFixed(1)),  // 体重范围60-70kg，转换为数值类型
      note: ''
    });

    // 中午数据 (12:00)
    date.setHours(12, 0, 0, 0);
    
    // 血糖数据
    storage.glucose.push({
      timestamp: date.getTime(),
      value: parseFloat((Math.random() * 3 + 5).toFixed(1)),
      period: 'noon'
    });
    
    // 添加血压数据 (12:00)
    storage.bloodPressure.push({
      timestamp: date.getTime(),
      systolic: Math.floor(Math.random() * 30 + 110),
      diastolic: Math.floor(Math.random() * 20 + 70),
      period: 'noon'
    });

    // 晚上数据 (18:00)
    date.setHours(18, 0, 0, 0);
    
    // 血糖数据
    storage.glucose.push({
      timestamp: date.getTime(),
      value: parseFloat((Math.random() * 3 + 5).toFixed(1)),
      period: 'evening'
    });
    
    // 添加血压数据 (18:00)
    storage.bloodPressure.push({
      timestamp: date.getTime(),
      systolic: Math.floor(Math.random() * 30 + 110),
      diastolic: Math.floor(Math.random() * 20 + 70),
      period: 'evening'
    });
  }
  
  console.log('[健康API] 测试数据添加完成，总计数据量:', {
    glucose: storage.glucose.length,
    bloodPressure: storage.bloodPressure.length,
    weight: storage.weight.length
  });
  
  // 标记为已初始化
  dataInitialized = true;
}

// 不再自动初始化数据
// initializeData();

/**
 * 获取健康记录
 * @param {Object} params - 查询参数
 * @param {string} params.type - 数据类型(glucose, bloodPressure, weight)
 * @param {string} params.startDate - 开始日期(可选)
 * @param {string} params.endDate - 结束日期(可选)
 * @param {number} params.limit - 返回记录限制数量(可选)
 * @returns {Promise<Array>} - 返回记录数组
 */
async function getRecords(params) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('[HealthAPI] API调用 getRecords 参数:', params);
      console.log('[HealthAPI] 当前storage数据:', storage);
      
      // 确保type大小写一致，转换为小写
      const normalizedType = params.type ? params.type.toLowerCase() : '';
      let storageKey = normalizedType;
      
      // 处理类型名称的不一致
      if (normalizedType === 'bloodpressure') {
        storageKey = 'bloodPressure';
      }
      
      console.log(`[HealthAPI] 查询数据类型: ${normalizedType} 映射到storage键: ${storageKey}`);
      
      let records = storage[storageKey] || [];
      console.log(`[HealthAPI] 从storage获取原始数据, 数量: ${records.length}`);
      
      // 如果有日期范围，进行过滤
      if (params.startDate && params.endDate) {
        const start = new Date(params.startDate).getTime();
        const end = new Date(params.endDate).getTime();
        records = records.filter(r => {
          const time = new Date(r.timestamp).getTime();
          return time >= start && time <= end;
        });
        console.log(`[HealthAPI] 日期过滤后的数据数量: ${records.length}`);
      }

      // 限制返回数量
      if (params.limit) {
        records = records.slice(0, params.limit);
      }
      
      console.log(`[HealthAPI] 最终返回的数据量: ${records.length}`);
      
      // 记录查询时间戳
      if (typeof wx !== 'undefined') {
        // 保存当前查询时间，以便下次比较是否有更新
        wx.getStorage({
          key: 'lastFetchTimes',
          success(res) {
            const times = res.data || {};
            times[storageKey] = Date.now();
            wx.setStorage({
              key: 'lastFetchTimes',
              data: times
            });
          },
          fail() {
            const times = {};
            times[storageKey] = Date.now();
            wx.setStorage({
              key: 'lastFetchTimes',
              data: times
            });
          }
        });
      }

      resolve(records);
    }, 200);
  });
}

/**
 * 添加健康记录
 * @param {string} type - 数据类型(glucose, bloodPressure, weight)
 * @param {Object} data - 记录数据
 * @returns {Promise<boolean>} - 操作是否成功
 */
async function addRecord(type, data) {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 确保type是正确的
      const normalizedType = type.toLowerCase();
      let storageKey = normalizedType;
      
      // 处理类型名称的不一致
      if (normalizedType === 'bloodpressure') {
        storageKey = 'bloodPressure';
      }
      
      // 添加时间段信息（如果是血糖或血压）
      if (storageKey === 'glucose' || storageKey === 'bloodPressure') {
        if (!data.period) {
          // 根据时间推断时间段
          const hour = new Date(data.timestamp).getHours();
          
          if (hour >= 6 && hour < 9) {
            data.period = 'morning';
          } else if (hour >= 9 && hour < 14) {
            data.period = 'noon';
          } else if (hour >= 14 && hour < 19) {
            data.period = 'evening';
          } else {
            data.period = 'night';
          }
          
          console.log(`[HealthAPI] 自动设置${storageKey}记录的时间段:`, data.period);
        }
      }
      
      // 添加记录到数据存储中
      storage[storageKey].unshift(data);
      if (storage[storageKey].length > 100) {
        storage[storageKey].pop();
      }
      
      console.log(`[HealthAPI] 添加${storageKey}记录成功:`, data);
      
      // 不再广播数据更新事件，避免每次添加记录时都触发数据刷新
      
      resolve(true);
    }, 200);
  });
}

/**
 * 更新健康记录
 * @param {string} type - 数据类型(glucose, bloodPressure, weight)
 * @param {string|number} timestamp - 记录时间戳
 * @param {Object} data - 更新数据
 * @returns {Promise<boolean>} - 操作是否成功
 */
async function updateRecord(type, timestamp, data) {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 确保type是正确的
      const normalizedType = type.toLowerCase();
      let storageKey = normalizedType;
      
      // 处理类型名称的不一致
      if (normalizedType === 'bloodpressure') {
        storageKey = 'bloodPressure';
      }
      
      const index = storage[storageKey].findIndex(r => r.timestamp === timestamp);
      if (index > -1) {
        // 保留原始timestamp
        const originalTimestamp = storage[storageKey][index].timestamp;
        // 更新记录，但保留原始timestamp
        storage[storageKey][index] = {
          ...data,
          timestamp: originalTimestamp
        };
        
        console.log(`[HealthAPI] 更新${storageKey}记录成功:`, storage[storageKey][index]);
        
        // 不再广播数据更新事件，避免每次更新记录时都触发数据刷新
        
        resolve(true);
      } else {
        resolve(false);
      }
    }, 200);
  });
}

/**
 * 删除健康记录
 * @param {string} type - 数据类型(glucose, bloodPressure, weight)
 * @param {string|number} timestamp - 记录时间戳
 * @returns {Promise<boolean>} - 操作是否成功
 */
async function deleteRecord(type, timestamp) {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 确保type是正确的
      const normalizedType = type.toLowerCase();
      let storageKey = normalizedType;
      
      // 处理类型名称的不一致
      if (normalizedType === 'bloodpressure') {
        storageKey = 'bloodPressure';
      }
      
      const index = storage[storageKey].findIndex(r => r.timestamp === timestamp);
      if (index > -1) {
        storage[storageKey].splice(index, 1);
        
        console.log(`[HealthAPI] 删除${storageKey}记录成功:`, timestamp);
        
        // 不再广播数据更新事件，避免每次删除记录时都触发数据刷新
      }
      
      resolve(true);
    }, 200);
  });
}

/**
 * 获取单条健康记录
 * @param {string} type - 数据类型(glucose, bloodPressure, weight)
 * @param {string|number} id - 记录ID(时间戳)
 * @returns {Promise<Object|null>} - 返回记录或null
 */
async function getRecord(type, id) {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 这里id实际上就是timestamp，但保持接口一致性
      const record = storage[type].find(r => r.timestamp === Number(id));
      resolve(record || null);
    }, 200);
  });
}

/**
 * 获取可用的数据类型选项
 * @returns {Array<Object>} - 数据类型选项
 */
function getTypeOptions() {
  return [
    { value: 'glucose', label: '血糖' },
    { value: 'bloodPressure', label: '血压' },
    { value: 'weight', label: '体重' }
  ];
}

/**
 * 获取血糖测量时段选项
 * @returns {Array<Object>} - 时段选项
 */
function getGlucosePeriodOptions() {
  return [
    { value: 'morning', label: '早餐前' },
    { value: 'after-breakfast', label: '早餐后' },
    { value: 'noon', label: '午餐前' },
    { value: 'after-noon', label: '午餐后' },
    { value: 'evening', label: '晚餐前' },
    { value: 'after-evening', label: '晚餐后' },
    { value: 'night', label: '睡前' },
    { value: 'other', label: '其它时间' }
  ];
}

/**
 * 获取最新的健康数据记录
 * @returns {Promise<Object>} - 返回最新的健康数据
 */
async function getLatestHealthData() {
  try {
    // 获取最新的体重记录
    const weightRecords = await getRecords({ type: 'weight', limit: 1 });
    const latestWeight = weightRecords.length > 0 ? weightRecords[0].value : 65;
    
    // 获取最新的血糖记录
    const glucoseRecords = await getRecords({ type: 'glucose', limit: 1 });
    const latestGlucose = glucoseRecords.length > 0 ? glucoseRecords[0].value : null;
    
    // 获取最新的血压记录
    const bpRecords = await getRecords({ type: 'bloodPressure', limit: 1 });
    const latestBP = bpRecords.length > 0 ? {
      systolic: bpRecords[0].systolic,
      diastolic: bpRecords[0].diastolic
    } : null;
    
    return {
      success: true,
      data: {
        weight: latestWeight,
        glucose: latestGlucose,
        bloodPressure: latestBP
      }
    };
  } catch (error) {
    console.error('获取最新健康数据失败:', error);
    return {
      success: false,
      message: '获取健康数据失败',
      error: error.message
    };
  }
}

/**
 * 保存风险评估结果到服务器
 * @param {Object} assessment - 风险评估记录
 * @returns {Promise<Object>} - 返回保存结果
 */
async function saveRiskAssessment(assessment) {
  // 首先尝试使用服务器API
  try {
    // 确保数据格式符合后端API要求
    const payload = {
      result: {
        prediction: assessment.result.prediction,
        probability: assessment.result.probability,
        riskLevel: assessment.result.riskLevel
      },
      inputData: assessment.inputData,
      measuredAt: assessment.timestamp
    };
    
    // 调用后端API
    const response = await request.post('/health/risk-assessment', payload);
    console.log('[HealthAPI] 保存风险评估记录到服务器成功:', response);
    
    // 刷新内存中的记录
    riskAssessmentStorage.unshift({
      ...assessment,
      _id: response.data._id
    });
    
    return response;
  } catch (error) {
    console.error('[HealthAPI] 保存风险评估记录到服务器失败:', error);
    
    // 服务器保存失败，回退到本地存储
    return new Promise((resolve) => {
      setTimeout(() => {
        // 添加记录到数据存储中
        riskAssessmentStorage.unshift(assessment);
        
        // 限制存储的记录数量，保留最新的100条
        if (riskAssessmentStorage.length > 100) {
          riskAssessmentStorage.pop();
        }
        
        // 保存到本地存储中，确保数据持久化
        try {
          wx.getStorage({
            key: 'risk_assessments',
            success(res) {
              const history = res.data || [];
              history.unshift(assessment);
              // 限制本地存储记录数量
              const savedHistory = history.slice(0, 100);
              wx.setStorage({
                key: 'risk_assessments',
                data: savedHistory,
                success: () => {
                  console.log('[HealthAPI] 风险评估记录保存到本地存储成功');
                },
                fail: (error) => {
                  console.error('[HealthAPI] 风险评估记录保存到本地存储失败:', error);
                }
              });
            },
            fail() {
              // 如果没有找到，则创建新记录
              wx.setStorage({
                key: 'risk_assessments',
                data: [assessment],
                success: () => {
                  console.log('[HealthAPI] 风险评估记录保存到本地存储成功');
                },
                fail: (error) => {
                  console.error('[HealthAPI] 风险评估记录保存到本地存储失败:', error);
                }
              });
            }
          });
        } catch (error) {
          console.error('[HealthAPI] 保存风险评估记录到本地存储出错:', error);
        }
        
        resolve({
          success: true,
          data: assessment,
          fromLocalStorage: true
        });
      }, 200);
    });
  }
}

/**
 * 获取风险评估历史记录
 * @param {Object} params - 查询参数
 * @param {string} params.startDate - 开始日期(可选)
 * @param {string} params.endDate - 结束日期(可选)
 * @param {number} params.limit - 返回记录限制数量(可选)
 * @param {number} params.page - 页码(可选)
 * @returns {Promise<Array>} - 返回风险评估历史记录
 */
async function getRiskAssessments(params = {}) {
  // 优先尝试从服务器获取数据
  try {
    const response = await request.get('/health/risk-assessment', params);
    console.log('[HealthAPI] 从服务器获取风险评估记录成功:', response);
    
    // 更新内存中的数据
    if (response.data.records && response.data.records.length > 0) {
      // 清空并重新填充内存存储
      riskAssessmentStorage.length = 0;
      response.data.records.forEach(record => {
        riskAssessmentStorage.push({
          _id: record._id,
          timestamp: record.measuredAt,
          result: record.result,
          inputData: record.inputData
        });
      });
    }
    
    return response.data.records || [];
  } catch (error) {
    console.error('[HealthAPI] 从服务器获取风险评估记录失败:', error);
    
    // 服务器获取失败，回退到本地存储
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log('[HealthAPI] 尝试从本地存储获取风险评估历史记录');
        
        try {
          // 从本地存储中获取数据
          wx.getStorage({
            key: 'risk_assessments',
            success(res) {
              let records = res.data || [];
              
              // 如果有内存中的数据，优先使用内存数据
              if (riskAssessmentStorage.length > 0) {
                records = [...riskAssessmentStorage];
              }
              
              // 根据时间戳排序
              records.sort((a, b) => {
                return new Date(b.timestamp) - new Date(a.timestamp);
              });
              
              // 处理日期过滤
              if (params.startDate || params.endDate) {
                records = records.filter(record => {
                  const recordDate = new Date(record.timestamp);
                  let matchesFilter = true;
                  
                  if (params.startDate) {
                    const startDate = new Date(params.startDate);
                    matchesFilter = matchesFilter && recordDate >= startDate;
                  }
                  
                  if (params.endDate) {
                    const endDate = new Date(params.endDate);
                    endDate.setHours(23, 59, 59, 999);
                    matchesFilter = matchesFilter && recordDate <= endDate;
                  }
                  
                  return matchesFilter;
                });
              }
              
              // 处理分页
              if (params.limit) {
                const limit = Number(params.limit);
                const page = Number(params.page || 1);
                const skip = (page - 1) * limit;
                records = records.slice(skip, skip + limit);
              }
              
              resolve(records);
            },
            fail() {
              // 如果本地存储没有数据，返回内存中的数据
              let records = [...riskAssessmentStorage];
              
              // 限制返回数量
              if (params.limit) {
                const limit = Number(params.limit);
                const page = Number(params.page || 1);
                const skip = (page - 1) * limit;
                records = records.slice(skip, skip + limit);
              }
              
              resolve(records);
            }
          });
        } catch (error) {
          console.error('[HealthAPI] 获取风险评估历史记录失败:', error);
          resolve(riskAssessmentStorage);
        }
      }, 200);
    });
  }
}

/**
 * 获取最新风险评估结果
 * @returns {Promise<Object|null>} - 返回最新评估或null
 */
async function getLatestRiskAssessment() {
  try {
    // 尝试从服务器获取最新记录
    const response = await request.get('/health/risk-assessment', { limit: 1 });
    if (response.data.records && response.data.records.length > 0) {
      return {
        _id: response.data.records[0]._id,
        timestamp: response.data.records[0].measuredAt,
        result: response.data.records[0].result,
        inputData: response.data.records[0].inputData
      };
    }
    
    // 如果服务器没有记录，尝试本地记录
    return getRiskAssessments({ limit: 1 }).then(assessments => {
      return assessments.length > 0 ? assessments[0] : null;
    });
  } catch (error) {
    console.error('[HealthAPI] 获取最新风险评估记录失败:', error);
    
    // 服务器查询失败，回退到本地查询
    return getRiskAssessments({ limit: 1 }).then(assessments => {
      return assessments.length > 0 ? assessments[0] : null;
    });
  }
}

/**
 * 获取风险评估统计信息
 * @param {Object} params - 查询参数
 * @param {number} params.days - 统计天数，默认90天
 * @returns {Promise<Object>} - 返回统计信息
 */
async function getRiskAssessmentStats(params = { days: 90 }) {
  try {
    const response = await request.get('/health/risk-assessment/stats', params);
    return response.data;
  } catch (error) {
    console.error('[HealthAPI] 获取风险评估统计数据失败:', error);
    
    // 回退到本地计算
    return getRiskAssessments().then(assessments => {
      // 过滤指定天数内的数据
      const days = params.days || 90;
      const startDate = new Date();
      startDate.setDate(startDate.getDate() - days);
      
      const filteredAssessments = assessments.filter(assessment => {
        return new Date(assessment.timestamp) >= startDate;
      });
      
      // 计算趋势
      let trend = 'stable';
      if (filteredAssessments.length >= 2) {
        const first = filteredAssessments[filteredAssessments.length - 1];
        const last = filteredAssessments[0];
        
        if (last.result.probability < first.result.probability - 0.05) {
          trend = 'decreasing';
        } else if (last.result.probability > first.result.probability + 0.05) {
          trend = 'increasing';
        }
      }
      
      // 计算分布
      const riskLevelDistribution = {
        '低风险': 0,
        '中风险': 0,
        '高风险': 0
      };
      
      filteredAssessments.forEach(assessment => {
        riskLevelDistribution[assessment.result.riskLevel]++;
      });
      
      return {
        totalAssessments: filteredAssessments.length,
        trend,
        riskLevelDistribution,
        latestAssessment: filteredAssessments.length > 0 ? filteredAssessments[0] : null
      };
    });
  }
}

/**
 * 删除风险评估记录
 * @param {string} id 记录的ID
 * @returns {Promise} 包含删除结果的Promise
 */
async function deleteRiskAssessment(id) {
  console.log(`[Health API] 删除风险评估记录: ${id}`);
  return request.delete(`/health/risk-assessment/${id}`);
}

module.exports = {
  getRecords,
  addRecord,
  updateRecord,
  deleteRecord,
  getRecord,
  getTypeOptions,
  getGlucosePeriodOptions,
  initializeData,
  getLatestHealthData,
  saveRiskAssessment,
  getRiskAssessments,
  getLatestRiskAssessment,
  getRiskAssessmentStats,
  deleteRiskAssessment
}; 